#include <QColor>
#include <QGuiApplication>
#include <QDebug>
#include <QPainter>
#include <QtMath>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QEventLoop>
#include <QShowEvent>
#include <QPushButton>
#include <QJsonDocument>
#include <QJsonObject>
#include <QScreen>
#include <QClipboard>
#include <QPainterPath>
#include <algorithm>

#include "MainWindow.h"
#include "ConfigData.h"


MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{

    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setFixedWidth(ConfigData::instance().ui->noteWindowWidth->get());


    // 关闭按钮
    QPushButton *closeButton = new QPushButton(this);
    closeButton->setGeometry(this->width()- 40, 12, 25, 25);
    closeButton->setFlat(true);
    //closeButton->setStyleSheet("QPushButton{border:none;}");
    closeButton->setIconSize(QSize(25, 25));
    closeButton->setIcon(QIcon(":/icons-x.png"));
    closeButton->setFocusPolicy(Qt::NoFocus);
    connect(closeButton, &QPushButton::clicked, this, &MainWindow::hide);

    // 固定按钮
    QPushButton *fixButton = new QPushButton(this);
    fixButton->setGeometry(this->width()- 70, 12, 25, 25);
    fixButton->setFlat(true);
    fixButton->setCheckable(true);
    fixButton->setChecked(ConfigData::instance().ui->isPinning->get());
    fixButton->setStyleSheet("QPushButton{border:none;} QPushButton:checked{background-color:rgb(222, 222, 222);}");
    fixButton->setIconSize(QSize(25, 25));
    fixButton->setIcon(QIcon(":/icons-pin-grey.png"));
    fixButton->setFocusPolicy(Qt::NoFocus);
    connect(fixButton, &QPushButton::clicked, this, [](bool checked){
        ConfigData::instance().ui->isPinning->set(checked);
    });

    // 刷新按钮
    refreshButton = new QPushButton(this);
    refreshButton->setGeometry(this->width()- 100, 12, 25, 25);
    refreshButton->setFlat(true);
    refreshButton->setIconSize(QSize(25, 25));
    refreshButton->setIcon(QIcon(":/icons-refresh.png"));
    refreshButton->setFocusPolicy(Qt::NoFocus);
    connect(refreshButton, &QPushButton::clicked, this, &MainWindow::onRefreshButtonPressed);

    // 星星按钮
    QPushButton *starButton = new QPushButton(this);
    starButton->setGeometry(this->width()- 130, 12, 25, 25);
    starButton->setFlat(true);
    starButton->setIconSize(QSize(25, 25));
    starButton->setFocusPolicy(Qt::NoFocus);
    starButton->setIcon(QIcon(":/icons-star.png"));

    // 声音按钮
//    QPushButton *voiceButton = new QPushButton(this->centralWidget());
//    voiceButton->setGeometry(this->width()- 160, 13, 25, 25);
//    voiceButton->setFlat(true);
//    voiceButton->setIconSize(QSize(25, 25));
//    voiceButton->setIcon(QIcon(":/icons-voice.png"));

    // 换行N按钮
    QPushButton *newLineButton = new QPushButton(this);
    newLineButton->setGeometry(this->width()- 160, 12, 25, 25);
    newLineButton->setFlat(true);
    newLineButton->setCheckable(true);
    newLineButton->setChecked(ConfigData::instance().translate->ignoreCRLF->get());
    newLineButton->setStyleSheet("QPushButton{border:none;} QPushButton:checked{background-color:rgb(222, 222, 222);}");
    newLineButton->setIconSize(QSize(25, 25));
    newLineButton->setIcon(QIcon(":/icons-n.png"));
    newLineButton->setFocusPolicy(Qt::NoFocus);
    connect(newLineButton, &QPushButton::clicked, this, [=](bool checked){
        ConfigData::instance().translate->ignoreCRLF->set(checked);
    });

    // 复制按钮
    QPushButton *copyButton = new QPushButton(this);
    copyButton->setGeometry(this->width()- 190, 13, 25, 25);
    copyButton->setFlat(true);
    copyButton->setIconSize(QSize(25, 25));
    copyButton->setIcon(QIcon(":/copy.png"));
    copyButton->setFocusPolicy(Qt::NoFocus);
    connect(copyButton, &QPushButton::clicked, this, &MainWindow::onCopyButtonPressed);

    // 翻译内容  NOTICE: 不要把上面按钮挡住了
    // stackWidget 里面有两个控件，0. 长文本翻译 1. wordPage
    centralWidget = new QWidget(this);
    centralWidget->setGeometry(20, 40, this->width() - 40, this->height() - 20 );

    Direction_Up = ConfigData::instance().ui->Up;
    Direction_Down = ConfigData::instance().ui->Down;
}

void MainWindow::showEvent(QShowEvent *e)
{
    if (Direction == Direction_Up)
    {
        // 三角形占用了上面的区域
        this->setFixedHeight(this->height() + ConfigData::instance().ui->triangleHeight->get());
    }
    e->ignore();
}

void MainWindow::paintEvent(QPaintEvent *event)
{

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    QPen pen;
    pen.setWidth(3);

    QBrush brush;
    brush.setStyle(Qt::SolidPattern);

    // 要根据皮肤设置颜色
    if (ConfigData::instance().ui->uiTheme->get() == ConfigData::instance().ui->Light)
    {
        pen.setColor(QColor(192, 192, 192));
        brush.setColor(Qt::white);
    }
    else
    {
        pen.setColor(QColor(100, 100, 100)); // dark
        brush.setColor(QColor("#323232"));
    }

    painter.setPen(pen);
    painter.setBrush(brush);

    QPolygon polygon;
    QPainterPath path;
    int TriangleWidth = ConfigData::instance().ui->triangleWidth->get();
    int TriangleHeight = ConfigData::instance().ui->triangleHeight->get();
    if (showTriangle == false)
    {
        move(0, 0);
        path.addRoundedRect(5, 5, this->width() -5 -5, this->height()-5-5 , 15, 15);
        //showTriangle = true;
    }
    else if (Direction == Direction_Down)
    {
        move(0, 0);
        path.moveTo(0, 0);
        path.arcMoveTo(5,5,30,30,90);
        path.arcTo(5,5,30,30,90, 90);
        path.lineTo(5, this->height() - TriangleHeight - 15);
        path.arcTo(5,this->height() - TriangleHeight - 30,30,30,180, 90);
        path.lineTo(this->width() / 2 - TriangleWidth + TriangleOffset, this->height() - TriangleHeight);
        path.lineTo(this->width() / 2 + TriangleOffset, this->height());
        path.lineTo(this->width() / 2 + TriangleWidth + TriangleOffset, this->height() - TriangleHeight);
        path.lineTo(this->width() -5 -15, this->height() - TriangleHeight);
        path.arcTo(this->width() -5 -30 ,this->height() - TriangleHeight - 30,30,30,270, 90);
        path.lineTo(this->width() -5 , 5+15);
        path.arcTo(this->width() -5 -30 ,5,30,30,0, 90);
        path.closeSubpath();

    }
    else if (Direction == Direction_Up)
    {
        move(x(), TriangleHeight);
        path.moveTo(0, 0);
        path.arcMoveTo(5,TriangleHeight,30,30,90);
        path.arcTo(5,TriangleHeight,30,30,90, 90);
        path.lineTo(5, this->height() - 5 -15 );
        path.arcTo(5,this->height() - 5 - 30,30,30,180, 90);
        path.lineTo(this->width() -5 -15, this->height() - 5);
        path.arcTo(this->width() -5 -30 ,this->height() - 5 - 30,30,30,270, 90);
        path.lineTo(this->width() -5 , TriangleHeight+15);
        path.arcTo(this->width() -5 -30 ,TriangleHeight,30,30,0, 90);
        path.lineTo(this->width() / 2 + TriangleWidth + TriangleOffset, TriangleHeight);
        path.lineTo(this->width() / 2 + TriangleOffset, 0);
        path.lineTo(this->width() / 2 - TriangleWidth + TriangleOffset, TriangleHeight);
        path.closeSubpath();
    }
    painter.drawPath(path);
    event->accept();
}

void MainWindow::onMouseButtonPressed(int x, int y)
{
    if (!this->isHidden() && (x < this->x() || x > this->x() + width() || y < this->y() || y > this->y() + height()))
        if (!ConfigData::instance().ui->isPinning->get())
            hide();

}

// 返回MainWindow弹出的位置
QPoint MainWindow::getAdjustedPosition(QPoint mousePressPosition, QPoint mouseReleasedPosition)
{
    // 获取默认方向向 重置三角形偏移量
    int direction = ConfigData::instance().ui->noteWindowDirection->get();
    TriangleOffset = 0;

    QPoint mid(0, 0);
    mid.rx() = (mousePressPosition.x() + mouseReleasedPosition.x() - width()) / 2;

    if (direction == Direction_Up)
        mid.ry() = std::max(mousePressPosition.y(), mouseReleasedPosition.y()) + 15;
    else
        mid.ry() = std::min(mousePressPosition.y(), mouseReleasedPosition.y()) - this->height() - 15;


    // 判断应该出现在哪个屏幕上
    QRect targetScreenRect;
    for (auto screen : QGuiApplication::screens())
    {
        if (screen->availableGeometry().contains((mousePressPosition + mouseReleasedPosition) / 2))
        {
            targetScreenRect = screen->availableGeometry();

            break;
        }
    }

    // 判断是否超出屏幕上边界
    if (direction == Direction_Down && mid.y() < targetScreenRect.y())
    {
        direction = Direction_Up;
        mid.ry() = std::max(mousePressPosition.y(), mouseReleasedPosition.y()) + 15;
    }
    // 判断是否超出屏幕下边界
    if (direction == Direction_Up && mid.y() + this->height() > targetScreenRect.y() + targetScreenRect.height())
    {
        direction = Direction_Down;
        mid.ry() = std::min(mousePressPosition.y(), mouseReleasedPosition.y()) - this->height() - 15;
    }
    Direction = direction;
    int edge = ConfigData::instance().ui->noteWindowEdge->get();
    int TriangleWidth = ConfigData::instance().ui->triangleWidth->get();
    // 判断是否超出屏幕左边界
    if (mid.x() < edge + targetScreenRect.x())
    {
        TriangleOffset = edge - (mid.x() - targetScreenRect.x());
        if (TriangleOffset > this->width() / 2 - TriangleWidth * 2)
            TriangleOffset = this->width() / 2 - TriangleWidth * 2;
        mid.rx() = edge + targetScreenRect.x();
        TriangleOffset = -TriangleOffset;
    }
    // 判断是否超出屏幕右边界
    if (mid.x() + this->width() > targetScreenRect.x() + targetScreenRect.width() - edge)
    {
        TriangleOffset = mid.x() - (targetScreenRect.x() + targetScreenRect.width() - edge - this->width());
        if (TriangleOffset > this->width() / 2 - TriangleWidth * 2)
            TriangleOffset = this->width() / 2 - TriangleWidth * 2;
        mid.rx() = targetScreenRect.x() + targetScreenRect.width() - edge - this->width();
    }

    return mid;
}


void MainWindow::onRefreshButtonPressed()
{

}

void MainWindow::onCopyButtonPressed()
{
    QClipboard *clipboard = QGuiApplication::clipboard();

}

void MainWindow::setCentralWidget(QWidget *widget)
{
    if (widget)
        widget->setParent(centralWidget);
}
